package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.dto.RegisterDto;
import com.example.demo.dto.UserLoginDto;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.Result;
import com.example.demo.utils.BCryptPasswordEncoder;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.OssUtil;
import com.example.demo.utils.PasswordEncoder;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@AllArgsConstructor
public class UserService {

    private UserMapper userMapper;
    private JwtUtils jwtUtils;
    private PasswordEncoder passwordEncoder;
    private OssUtil ossUtil;

    public Result login(UserLoginDto userLoginDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", userLoginDto.getUsername());

        User user = userMapper.selectOne(queryWrapper);

        if(null == user || !passwordEncoder.matches(userLoginDto.getPassword(),user.getPassword())) {
            return Result.buildFail("用户名或密码错误");
        }else {
            // 构建jwt
            Object jwt = jwtUtils.createAccessToken(user.getUsername());
            // 往前端返回jwt字符串
            return Result.buildSuccess(jwt);
        }
    }

    public Result register(RegisterDto registerDto) {

        if(userMapper.checkUser(registerDto.getUsername()) == null) {
            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            User user = new User();
            user.setPassword(passwordEncoder.encode(registerDto.getPassword()));
            user.setEmail(registerDto.getEmail());
            user.setUsername(registerDto.getUsername());
            user.setModTime(new Date());
            user.setRegTime(new Date());
            user.setUserImg("https://spring1024.oss-cn-beijing.aliyuncs.com/2022/02/18/c8ce540727bc4b708e002ddc14bdbaaf111.png");
//        ossUtil.uploadFileAvatar("")

            userMapper.Register(user);
            return Result.buildSuccess();
        }else {
            return Result.buildFail("用户名已存在");
        }


    }
}
